<template>
  <el-dialog :visible.sync="dialogAddVisible"
             append-to-body
             width="40%"
             @closed="emitAutoInput"
             :close-on-click-modal="false"
             title="检验结果录入">
    <div class="csstop">
        <div class="cssborder"></div>
        <div class="cssborder2"></div>
        <div class="cssborder3"></div>
    </div>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="12">
        <div class="el-dialog-item"><label>样品规格<i class="i_colon">：</i></label><span>{{detailData.materialType}}</span></div>
      </el-col>
      <el-col :span="12">
        <div class="el-dialog-item"><label class="w3">检验号</label><i class="i_colon">：</i><span style="color: #cb0000;font-size: 14px;">{{detailData.sampleId}}</span></div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <div class="el-dialog-item"><label>物料编码<i class="i_colon">：</i></label><span>{{detailData.materialCode}}</span></div>
      </el-col>
      <el-col :span="12">
        <div class="el-dialog-item"><label class="w3">申请人</label><i class="i_colon">：</i><span>{{detailData.userName}}</span></div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <div class="el-dialog-item"><label>样品名称<i class="i_colon">：</i></label><span>{{detailData.materialName}}</span></div>
      </el-col>
      <el-col :span="12">
        <div class="el-dialog-item"><label>申请时间<i class="i_colon">：</i></label><span>{{detailData.createTimeFt}}</span></div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <div class="el-dialog-item"><label>样品等级<i class="i_colon">：</i></label><span>{{detailData.materialGrade}}</span></div>
      </el-col>
      <el-col :span="12">
        <div class="el-dialog-item"><label>送样地点<i class="i_colon">：</i></label><span>{{detailData.location}}</span></div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <div class="el-dialog-item"><label>样品规模<i class="i_colon">：</i></label><span>{{detailData.sampleType}}</span></div>
      </el-col>
      <el-col :span="12">
        <div class="el-dialog-item"><label>样品批号<i class="i_colon">：</i></label><span>{{detailData.sampleNum}}</span></div>
      </el-col>
    </el-row>
    <div class="flex-row-space-between" style="float: left;">
      <div style="line-height:15px; font-size:13px;"><span style="color:#878989">检项数量<i class="i_colon">：</i></span><span>{{item.tableData.length}}/{{item.tableData.length}}</span></div>
    </div>

    <div class="upLoad_icon">
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        multiple
        :on-exceed="handleExceed"
        :on-change="handleChange"
        :file-list="filePaths"
        :before-upload="beforeAvatarUpload"
        accept=".jpg,.jpeg,.png,.gif,.pdf,.bmp"
        :limit="5">
        <i class="el-icon-upload zll_load"> 文件上传</i>
      </el-upload>
    </div>
    <div style="clear: both;"></div>
    <div class="el-dialog-table">
      <drug-table :cellOver="cellOver" :filterPage="false" ref="taskTable" :tableData="item.tableData" :tableLoading="item.tableLoading"
                   :tableHeader="item.tableHeader" >
      </drug-table>
    </div>


    <div class="flex-row-space-between" v-show="resetItem.tableData.length >0"
         style="margin-top:10px">
      <div style="line-height:15px; font-size:13px;"><span style="color:#878989">复检项<i class="i_colon">：</i></span></div>

      <div class="upLoad_icon">
        <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          multiple
          :on-exceed="handleResetExceed"
          :on-change="handleResetChange"
          :file-list="resetFilePaths"
          :before-upload="beforeResetAvatarUpload"
          accept=".jpg,.jpeg,.png,.gif,.pdf,.bmp"
          :limit="5">
          <i class="el-icon-upload zll_load"> 文件上传</i>
        </el-upload>
      </div>
    </div>
    <div class="el-dialog-table el-div-review" v-show="resetItem.tableData.length >0">
      <drug-table   :filterPage="false" ref="taskResetTable" :tableData="resetItem.tableData" :tableLoading="item.tableLoading"
                   :tableHeader="resetItem.tableHeader"  >
      </drug-table>
    </div>

    <div slot="footer" v-show="submitBut"
         class="dialog-footer">
      <el-button type="green"  v-if="type !='see'" class="zll_dialog_bt"
                 size="mini"
                 @click="takeTaskEvent"
                >
        提 交
      </el-button>

      <el-button type="warning"  v-if="type !='see'" class="zll_dialog_bt"
                 size="mini"
                 @click="takeTaskEvent('temp')"
                >
        暂 存
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import drugTable from "@/components/table/editTable";
  export default {
    name:"myTask",
    data(){
      return{
        testResult: '',
        isPop: false,
        detailData: {
          materialType:"",
          sampleId:"",
          materialCode:"",
          userName:"",
          materialName:"",
          createTimeFt:"",
          materialGrade:"",
          location:"",
          sampleType:"",
          filePath:"",
          filePaths:[],
          resetFilePaths:[],
          filePathName:"",
          resetPath:"",
          checkStatus:"",
          resetPathName:""
        },
        dialogAddVisible: false,
        cellOver: false,
        count: 0,
        type:"",
        staffId:"",
        item:{
          tableData: [],
          tableHeader:[],
          tableLoading:true,
        },
        resetItem:{
          tableData: [],
          tableHeader:[],
        },

        submitBut:true,
        loginMap:{},



        filePaths:[],
        resetFilePaths:[],

        fileName: '',
        fileNameTitle:'',
        resetFileName: '',
        resetFileNameTitle: '',

      }
    },
    watch: {
      isPop(val) {
        this.isPop = val
      }
    },
    mounted(){
      let self = this;
      self.getAllLogin();
      self.$eventBus.$on("openMyTaskDialog",function (editData,operateType,staffId) {
        self.dialogAddVisible = true;
        self.count = 0;
        self.type = operateType;
        self.staffId = staffId;
        self.detailData = editData;
        self.fileName = '';
        self.getSampleItems();
        self.getSampleDetail();

      })
      self.$eventBus.$on("openShowPopInput", function(listData,inputModel) {
        if(!inputModel) {
          self.isPop = false
        }else {
          for(let i = 0; i < self.item.tableData.length;i++){
            if (self.item.tableData[i].id = listData.id) {
              self.isPop = true
            }
          }
        }
      })
    },
    components:{
      drugTable
    },
    methods:{
      beforeAvatarUpload(file){
        if (!/.(jpg|jpeg|png|gif|pdf|bmp)$/.test(file.name)){
          this.$notify({title: '提示', message: "上传文件格式不对，请重新上传", type: 'warning'});
          return false;
        }
        if(file.size/1024/1024 > 20){
          this.$notify({title: '提示', message: "上传的文件小于20M！", type: 'warning'});
          return false;
        }
        return true;
      },

      handleExceed(files, fileList) {
        this.$notify({
          title: '提示',
          message: "当前限制选择 1 个文件，本次已经选择了"+ files.length+" 个文件，请您先删除文件！",
          type: 'warning'
        });
      },
      handleChange(file, fileList) {
        let self = this;
        self.filePaths = [];
        for(let i = 0; i < fileList.length;i++){
          let f = fileList[i];
          let fileObj = {name:f.name,fileName:f.name,fileBlob:"",id:self.detailData.sampleId,fileType:'code'};
          if(f.fileBlob){
            self.filePaths.push(f);
            continue;
          }
          let reader = new FileReader();
          reader.readAsDataURL(f.raw);
          reader.onload = function (e) {
            fileObj.fileBlob = e.currentTarget.result;
            self.filePaths.push(fileObj);
          };
        }
        console.log(self.filePaths)
      },

      beforeResetAvatarUpload(file){
        if (!/.(jpg|jpeg|png|gif|pdf|bmp)$/.test(file.name)){
          this.$notify({title: '提示', message: "上传文件格式不对，请重新上传", type: 'warning'});
          return false;
        }
        if(file.size/1024/1024 > 20){
          this.$notify({title: '提示', message: "上传的文件小于20M！", type: 'warning'});
          return false;
        }
        return true;
      },

      handleResetExceed(files, fileList) {
        this.$notify({
          title: '提示',
          message: "当前限制选择 1 个文件，本次已经选择了"+ files.length+" 个文件，请您先删除文件！",
          type: 'warning'
        });
      },
      handleResetChange(file, fileList) {
        let self = this;
        self.resetFilePaths = [];
        for(let i = 0; i < fileList.length;i++){
          let f = fileList[i];
          let fileObj = {name:f.name,fileName:f.name,fileBlob:"",id:self.detailData.sampleId,fileType:'reset'};
          if(f.fileBlob){
            self.resetFilePaths.push(f);
            continue;
          }
          let reader = new FileReader();
          reader.readAsDataURL(f.raw);
          reader.onload = function (e) {
            fileObj.fileBlob = e.currentTarget.result;
            self.resetFilePaths.push(fileObj);
          };
        }
      },


      getAllLogin(){
        let self = this;
        let loginMap = {};
        self.$http({
          url: "/drug/queryAllLoginList",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            for(let data of resp.result){
              loginMap[data.id] = data.userName;
            }
            self.loginMap = loginMap;
          }
        });
      },

      getSampleImageFile(){
        let self = this;
        self.$http({
          url: "/drug/images/queryImagesListById",
          method: "post",
          params:{id:self.detailData.sampleId}
        }).then(resp => {
          if (resp.success) {
            let filePaths = [];
            let resetFilePath = [];
            for(let data of resp.result){
               if(data.fileType == 'code'){
                 data.name = data.fileName;
                 filePaths.push(data);
               }
              if(data.fileType == 'reset'){
                data.name = data.fileName;
                resetFilePath.push(data);
              }
            }
            self.filePaths = filePaths;
            self.resetFilePaths = resetFilePath;
          }
        });
      },

      emitAutoInput(){
        this.$eventBus.$emit("autoInputJJ");
        this.isPop = false
      },
      getSampleDetail(){
        let self = this;
        self.tableLoading = true;
        self.$http({
          url: "/drug/sampleItem/querySampleWithPrint",
          method: "post",
          params:{sampleCode:self.detailData.sampleId}
        }).then(resp => {
          if (resp.success) {
            for(let key in self.detailData){
              if(!resp.result.hasOwnProperty(key)){
                resp.result[key] = self.detailData[key];
              }
            }
            self.detailData = resp.result;
            self.getSampleImageFile();
          }
        });
      },

      uploadSampleFile() {
        document.getElementById("sampleFile").click();
      },

      uploadSampleResetFile() {
        document.getElementById("sampleResetFile").click();
      },

      uploadFileSample(event){
        let self = this;
        let fileList = event.target.files;
        if (fileList.length > 0) {
          self.detailData.filePaths = [];
          let fileNameTitle = '';
          for(let i = 0; i < fileList.length;i++){
            let file = fileList[i];
            fileNameTitle +=  file.name+'\n'
            let fileObj = {fileName:file.name,fileBlob:"",id:self.detailData.sampleId,fileType:'code'};
            if (/.(jpg|jpeg|png|gif|pdf|bmp)$/.test(file.name)) {
              let reader = new FileReader();
              reader.readAsDataURL(file);
              reader.onload = function (e) {
                fileObj.fileBlob = e.currentTarget.result;
                self.detailData.filePaths.push(fileObj);
                self.fileNameTitle = fileNameTitle;
              	self.fileName = self.detailData.filePaths.length + '个文件'
              };
            } else {
              self.$notify({
                title: '提示',
                message: "上传文件必须是图片或pdf或压缩包！",
                type: 'warning'
              });
              self.detailData.filePaths = [];
              self.fileNameTitle = '';
              self.fileName = '0个文件'
              let obj = document.getElementById('sampleFile') ;
              obj.outerHTML = obj.outerHTML;
              break;
            }
          }
        }else{
          self.detailData.filePaths= [];
          self.fileName = '0个文件'
          self.fileNameTitle = '';
        }
      },
      uploadFileResetSample(event){
        let self = this;
        let fileList = event.target.files;
        if (fileList.length > 0) {
          self.detailData.resetFilePaths = [];
          for(let i = 0; i < fileList.length;i++){
            let file = fileList[i];
            let fileNameResetTitle = '';
            fileNameResetTitle +=  file.name+'\n'
            let fileObj = {fileName:file.name,fileBlob:"",id:self.detailData.sampleId,fileType:'reset'};
            if (/.(jpg|jpeg|png|gif|pdf|bmp)$/.test(file.name)) {
              let reader = new FileReader();
              reader.readAsDataURL(file);
              reader.onload = function (e) {
                fileObj.fileBlob = e.currentTarget.result;
                self.detailData.resetFilePaths.push(fileObj);
                self.resetFileNameTitle = fileNameResetTitle;
                self.resetFileName = self.detailData.resetFilePaths.length + '个文件'
              };
            } else {
              self.$notify({
                title: '提示',
                message: "上传文件必须是图片！",
                type: 'warning'
              });
              self.detailData.resetFilePaths = [];
              self.resetFileName = '0个文件';
              self.resetFileNameTitle = ''
              let obj = document.getElementById('sampleResetFile') ;
              obj.outerHTML = obj.outerHTML;
              break;
            }
          }
        }else{
          self.detailData.resetFilePaths = [];
          self.resetFileName = '0个文件'
          self.resetFileNameTitle = ''
        }
      },


      takeTaskEvent(type){
        let self = this;
        if(type !="temp"&&!self.checkSample()){
          return;
        }
        let detailData = {
          sampleCode:this.detailData.sampleId,
          filePath:this.detailData.filePath,
          filePaths:this.filePaths,
          resetFilePaths:this.resetFilePaths,
          filePathName:this.detailData.filePathName,
          resetPath:this.detailData.resetPath,
          resetPathName:this.detailData.resetPathName,
          standardItems:[],
          standardResetItems:[]
        };
        let tableData = this.$refs.taskTable.getTableData();
        let params = [];
        for(let data of tableData){
          if((data.resultId && data.resultId.value)||type =="temp"){
            let resultId = data.resultId.value;
            if(resultId =='合格'){
              resultId = "Y";
            }
            if(resultId =='不合格'){
              resultId = "N";
            }

            let param = {testResult:data.testResult.value,remark:data.remark.value,id:data.id,resultId:resultId,testStaffId:self.$store.getters.userId};
            if(type !="temp"){
              param.checkStatus = "SA"
            }
            params.push(param);
          }
        }
        detailData.standardItems = params;

        let tableResetData = this.$refs.taskResetTable.getTableData();
        let resetParams = [];
        for(let data of tableResetData){
          if((data.resultId && data.resultId.value)||type =="temp"){
            let resultId = data.resultId.value;
            if(resultId =='合格'){
              resultId = "Y";
            }
            if(resultId =='不合格'){
              resultId = "N";
            }
            let testResult = data.testResult?data.testResult.value:'';
            let param = {id:data.id,resultId:resultId,testResult:testResult};
            resetParams.push(param);
          }
        }
        detailData.standardResetItems = resetParams;

        detailData.userId = self.$store.getters.userId;
        detailData.userName = self.$store.getters.userName;
        if (this.count == 0) {
          self.$http({
            url: "/drug/sampleItem/takeSampleItem",
            method: "post",
            data: JSON.stringify(detailData),
            dataType: 'json',
            contentType: "application/json",
          }).then(resp => {
            if (resp.success) {
              self.$notify({
                title: '提示',
                message: "操作成功！",
                type: 'success'
              });
              self.dialogAddVisible = false;
              if(type !="temp"){
                self.insertFmApprove((resetParams.length > 0||self.detailData.checkStatus =='RJ')?"1":"");
              }
              return
            }
            self.$notify({
              title: '提示',
              message: "出现异常，请联系管理员",
              type: 'error'
            });
            this.count--;
          });
          this.count++;
        }
      },

      insertFmApprove(type){
        let self = this;
        let param = {insertValue:type,sampleCode:self.detailData.sampleId,relateId:self.detailData.sId,type:"4"};
        self.$http({
          url: "/drug/sampleItem/insertFmApprove",
          method: "post",
          params:param
        }).then(resp => {
          self.$eventBus.$emit("updateDetectionList");
        });
      },

      checkSample(){
        let tableData = this.$refs.taskTable.getTableData();
        let resetData = this.$refs.taskResetTable.getTableData();
        for(let data of tableData){
          if(!data.resultId.value){
            this.$notify({
              title: '提示',
              message: "检测结果不能为空！",
              type: 'warning'
            });
            return false;
          }
        }
        for(let data of resetData){
          if(!data.resultId.value){
            this.$notify({
              title: '提示',
              message: "复检项结果不能为空！",
              type: 'warning'
            });
            return false;
          }
        }
        return true;
      },

      getSampleItems(){
        let self = this;
        self.item.tableLoading = true;
        // self.submitBut = false;
        self.submitBut = true;
        self.$http({
          url: "/drug/sampleItem/querySampleItemSend",
          method: "post",
          params:{sampleCode:self.detailData.sampleId}
        }).then(resp => {
          if (resp.success) {
            self.item.tableLoading = false;
            let datas = [];
            let datasId = [];
            for(let data of resp.result.items){
              if(data.testStaffId == self.$store.getters.userId ||(self.staffId&& data.testStaffId == self.staffId)){
                data.itemName = {value:data.itemName};
                data.itemQualityStandard = {value:data.itemQualityStandard};
                if(data.resultId == "Y"){
                  data.resultIdCn="合格";
                }
                if(data.resultId == "N"){
                  data.resultIdCn="不合格";
                }
                data.testStaffIdCn = {value:self.loginMap[data.testStaffId],type:"input"};
                if(self.type !='see'&&resp.result.itemResets.length == 0){
                  data.testResult = {value:data.testResult||'',type:"input",edit:false,showTextarea:true};
                  data.resultId = {value:data.resultIdCn,edit:false,type:"select"};
                  data.remark = {value:data.remark,type:"input",edit:false};
                }else{
                  data.testResult = {value:data.testResult,type:"input"};
                  data.resultId = {value:data.resultIdCn,type:"select"};
                  data.remark = {value:data.remark,type:"input"};
                }

                // if(data.resultId){
                //   data.resultId = {value:data.resultIdCn,type:"select"};
                // }else{
                //   data.resultId = {value:data.resultIdCn,edit:false,type:"select"};
                // }
                datas.push(data);
                datasId.push(data.id);
              }
            }
            self.item.tableData = datas;
            self.item.tableHeader =  [
              {"columnName": "itemName", "coloumNameCn": "检项名称"},
              {"columnName": "itemQualityStandard", "coloumNameCn": "质量标准"},
              {"columnName": "testResult", "coloumNameCn": "检验结果"},
              {"columnName": "resultId", "coloumNameCn": "判定结果"},
              {"columnName": "remark", "coloumNameCn": "备注"},
               ];
            if(self.type =='see'){
              let personRow =  {"columnName": "testStaffIdCn", "coloumNameCn": "检测人"};
              self.item.tableHeader.push(personRow);
            }
            let resetDatas = [];
            for(let data of resp.result.itemResets){
              if(datasId.indexOf(data.sampleItemId) > -1){
                if(!data.resultId){
                  self.submitBut = true;
                }
                data.itemName = {value:data.itemName};
                data.itemQualityStandard = {value:data.itemQualityStandard};
                if(data.resultId == "Y"){
                  data.resultIdCn="合格";
                }
                if(data.resultId == "N"){
                  data.resultIdCn="不合格";
                }
                if(self.type !='see'){
                  data.resultId = {value:data.resultIdCn,edit:false,type:"select"};
                  data.testResult = {value:data.testResult||'',edit:false,type:"input",showTextarea:true};
                }else{
                  data.testResult = {value:data.testResult,type:"input"};
                  data.resultId = {value:data.resultIdCn,type:"select"};
                }
                resetDatas.push(data);
              }
            }
            self.resetItem.tableData = resetDatas;
            self.resetItem.tableHeader =  [
              {"columnName": "itemName", "coloumNameCn": "检项名称"},
              {"columnName": "itemQualityStandard", "coloumNameCn": "质量标准"},
              {"columnName": "testResult", "coloumNameCn": "检验结果"},
              {"columnName": "resultId", "coloumNameCn": "判定检验"} ];

          }
        });
      }
    }
  }
</script>
<style lang="scss" scoped>
    .zll_load {
        color: #34bfc6;    margin-right: 10px;
    }
	.upLoad_icon {
		position: relative;
		float: right;
		.btn {
			width: 80px;
            height: 20px;
            background: #2e827f;
            color: #fff;
            text-align: center;
            line-height: 20px;
            cursor: pointer;
            border-radius: 5px;
            font-size: 12px;
            display: inline-block;
		}
		.change {
			width: 100%;
            height: 20px;
            position: absolute;
            left: 0px;
            top: 0;
            z-index:1;
            opacity: 0;  /*css属性——opcity不透明度，取值0-1*/
            cursor: pointer;
		}
		.file_name {
			float: left;
            height: 20px;
            line-height: 20px;
            padding-right: 5px;
            font-size: 12px;
		}
        .upload-demo {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            width: 100%;
        }
	}

  .upLoad_icon {
    position: relative;
    display: flex;
    flex-direction: row;
    .btn {
      width: 100px;
      /*color: #34bfc6;*/
      text-align: center;
      cursor: pointer;
      border-radius: 5px;
      font-size: 14px;
      display: inline-block;
    }
    .change {
      width: 100%;
      position: absolute;
      left: 0px;
      top: 0;
      z-index:1;
      opacity: 0;  /*css属性——opcity不透明度，取值0-1*/
      cursor: pointer;
    }
    .file_name {
      font-size: 13px;
      width: calc(100% - 100px);
      p {
        margin: 0;
        line-height: 18px;
      }
      .fileTarget {
        .list {
          margin: 0; line-height: 18px;
          .closeFile {
            cursor: pointer;
            &:hover {
              background: #f3f3f3;
            }
          }
        }
      }
    }
  }

</style>
